package org.mycub.server.parser;

import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.json.JSONObject;
import org.mycub.server.data.models.TramStation;
import org.mycub.server.datainserter.TramStationsInserter;
import org.mycub.server.datainserter.factory.TramStationsInserterFactory;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;


public class CollectTramStation extends CollectItem{

	private TramStation tramStation;

	public CollectTramStation(){
		this.setTramStation(new TramStation());
	}

	public void collect(SimpleFeature feature){		

		String ident = (String) feature.getAttribute(0);
		Point point = (Point) feature.getAttribute(1);
		String address = (String) feature.getAttribute(2);
		String codePos = (String) feature.getAttribute(3);
		String line = (String) feature.getAttribute(4);
		String name = (String) feature.getAttribute(5);
		String city = (String) feature.getAttribute(6);
		
		String addressModel = address + " - " + codePos + " " + city;
		Geometry env = point.getEnvelope();
		try {
			
			env = JTS.toGeographic(env,CRS.decode("EPSG:3945"));
			
		} catch ( TransformException | FactoryException e ) {
			e.printStackTrace();
		}

		TramStation tramStationCollected = new TramStation();
		tramStationCollected.setId(ident);
		tramStationCollected.setLongitude(env.getCoordinates()[0].x);
		tramStationCollected.setLatitude(env.getCoordinates()[0].y);
		tramStationCollected.setLine(line);
		tramStationCollected.setAddress(addressModel);
		tramStationCollected.setName(name);

		this.setTramStation(tramStationCollected);

		System.out.println("collected tram station : " + tramStationCollected.getName() + 
				" id = " + tramStationCollected.getId());

		saveTramStation(tramStationCollected);
	}

	public void saveTramStation(TramStation tramStationCollected){
		TramStationsInserter tramStationsInserter = new TramStationsInserterFactory().createTramStationsInserter();
		tramStationsInserter.save(tramStationCollected);
	}

	public TramStation getTramStation() {
		return tramStation;
	}

	public void setTramStation(TramStation tramStation) {
		this.tramStation = tramStation;
	}

	@Override
	public void collect(JSONObject json) {		
	}
}
